#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qfiledialog.h"
#include "qpixmap.h"
#include "qdesktopwidget.h"
#include "qmessagebox.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
    , icon(":/images/icon.svg")
{
    QString name = tr("Timelapser");
    ui->setupUi(this);
    setWindowIcon(icon);
    systray.setIcon(icon);
    setWindowTitle(name);
    systray.show();
    systray.setToolTip(name);
    systray.showMessage(tr("Timelapser started!"),
                        tr("Timelapser captures and makes timelapse movies"),
                        QSystemTrayIcon::Information);
    connect(&systray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                 this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

    QMenu* menu = new QMenu(this);
    systray.setContextMenu(menu);

    QCompleter *completer = new QCompleter(this);
    QDirModel* model = new QDirModel(completer);
    model->setFilter( QDir::Dirs | QDir::Drives | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    completer->setModel(model);
    ui->screenshotFolder->setCompleter(completer);

    QAction* action;

    action = new QAction(tr("Quit"), this);
    connect(action, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(&timer, SIGNAL(timeout()), this, SLOT(timerTriggered()));
    menu->addAction(action);
    updateEnables();
    updateSampleText();

    QStringList types;
    types << "png" << "bmp" << "jpg" << "jpeg"
            << "mng" << "pbm" << "gif" << "pgm"
            << "ppm" << "tiff" << "xbm" << "xpm";
    ui->imageTypes->addItems(types);
    ui->imageTypes->setCurrentIndex( 0 );

    ui->quality->setValue(80);
}

void MainWindow::closeEvent(QCloseEvent* event)
 {
     if (systray.isVisible()) {
         systray.showMessage(tr("Timelapser hidden!"),
                             tr("To get it back, doubleclick it's icon. To quit select 'Quit' from its context menu or middle click on it's icon"),
                             QSystemTrayIcon::Information);
         hide();
         event->ignore();
     }
 }

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason)
    {
    case QSystemTrayIcon::Trigger:
        if( isMinimized() )
        {
            showNormal();
        }

        if( isActiveWindow() == false )
        {
            activateWindow();
        }
        break;
    case QSystemTrayIcon::DoubleClick:
        if( isVisible() )
        {
            systray.showMessage(tr("Timelapser hidden!"),
                                tr("Timelapser can be restored by double clicking this icon"),
                                QSystemTrayIcon::Information);
            hide();
        }
        else
        {
            if( isMinimized() )
            {
                showNormal();
            }
            else
            {
                show();
            }
            activateWindow();
        }
        break;
    case QSystemTrayIcon::MiddleClick:
        qApp->quit();
        break;
    default:
        break;
    }
}

void MainWindow::on_browseScreenshotFolder_clicked()
{
    QString folder = QFileDialog::getExistingDirectory(this);
    if( folder.isEmpty() == false )
    {
        ui->screenshotFolder->setText( folder );
    }
}

QString MainWindow::getSuggestedFile(const QString& name)
{
    QString folder = ui->screenshotFolder->text();
    if( folder.isEmpty() )
    {
        return "";
    }
    QDir path(folder);
    path.makeAbsolute();
    QString file = path.filePath(name);
    return file;
}

QString MainWindow::getSuggestedImageName(const QString& name)
{
    QString extension = ui->imageTypes->currentText();
    return QString("%1.%2").arg(name).arg(extension);
}

QString MainWindow::saveScreenshot(const QString& name, QString* ofile)
{
    QString file = getSuggestedFile( getSuggestedImageName(name) );
    if( ofile )
    {
        *ofile = file;
    }
    if( file.isEmpty() )
    {
        return tr("No folder given");
    }
    QPixmap img = QPixmap::grabWindow(QApplication::desktop()->winId());
    bool ok = img.save(file, 0, ui->quality->value());
    if( ok == false ) return tr("Failed to save %1").arg(file);
    return "";
}

QString GetSampleName()
{
    return "sample";
}

void MainWindow::on_testScreenshotFolder_clicked()
{
    QString file;
    QString error = saveScreenshot(GetSampleName(), &file);
    if( error.isEmpty() )
    {
        QMessageBox::information(this, tr("Image saved"), tr("Image saved to %1").arg(file));
    }
    else
    {
        QMessageBox::warning(this, tr("Image was not saved!"), error);
    }
}

void MainWindow::on_useScreenshot_clicked()
{
    updateEnables();
}

void MainWindow::updateEnables()
{
    bool started = timer.isActive();
    bool screenshot = ui->useScreenshot->isChecked();
    bool canStart = started == false;
    bool general = canStart && screenshot;
    bool screenshotButtons = screenshot && canStart;

    ui->stop->setEnabled(started == true);
    ui->start->setEnabled(general);

    ui->imageTypes->setEnabled(general);
    ui->interval->setEnabled(general);

    ui->screenshotFolder->setEnabled(screenshotButtons);
    ui->browseScreenshotFolder->setEnabled(screenshotButtons);
    ui->testScreenshotFolder->setEnabled(screenshotButtons);
}

void MainWindow::timerTriggered()
{
    QString name = QDateTime::currentDateTime()
                   .toString("yyyy MM dd hh mm ss zzz");

    QString error = saveScreenshot(name, 0);
    if( error.isEmpty() == false )
    {
        systray.showMessage(tr("Timelapser timer error!"),
                            error, QSystemTrayIcon::Critical);
    }
}

void MainWindow::on_start_clicked()
{
    QTime t = ui->interval->time();
    const int ms = t.msec() + (t.second() + t.minute() * 60 ) * 1000;
    if( getSuggestedFile(getSuggestedImageName(GetSampleName())).isEmpty() )
    {
        QMessageBox::critical(this, tr("Timelapse not started"), tr("You didn't enter a valid folder"));
        return;
    }

    if( ms < 100 )
    {
        QMessageBox::critical(this, tr("Timelapse not started"), tr("Didn't start timelapse, because of a low interval."));
        return;
    }

    timer.start(ms);
    updateEnables();
}

void MainWindow::on_stop_clicked()
{
    timer.stop();
    updateEnables();
}

void MainWindow::updateSampleText()
{
    QString file = getSuggestedFile(getSuggestedImageName(GetSampleName()));
    if( file.isEmpty() )
    {
        ui->sampleTarget->setText(tr("No folder given"));
    }
    else
    {
        ui->sampleTarget->setText(tr("Will create file as %1").arg(file));
    }
}

void MainWindow::on_screenshotFolder_textChanged(QString)
{
    updateSampleText();
    updateEnables();
}

void MainWindow::on_imageTypes_currentIndexChanged(int index)
{
    updateSampleText();
}
